<?php
require_once '../include/config.php';
require_once '../include/utils.class.php';
require_once '../include/orm.class.php';
require_once 'meta.php';

session_id($_POST["PHPSESSID"]);
session_start();

if (!isset($_SESSION[IS_AUTHENTICATED])) {
  return;
}

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  //获得上传文件信息
  $upload_file = $_FILES['Filedata'];
  //获取文件扩展名
  $file_info = pathinfo($upload_file['name']);
  $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
  
  //获取客户端参数
  $action = $_POST['action'];
  
  //Add custom code here...
  $updir = EXT_DIR . "$action/" . $file_info['filename'];
  $result = new stdClass();
  if (file_exists($updir)) {
    unlink($upload_file['tmp_name']);
    echo '"' . $file_info['filename'] . '": Existed';
    return;
  }
  
  Utils::create($updir);
  
  $zip = new ZipArchive;
  if ($zip->open($upload_file['tmp_name']) === TRUE) {
    $zip->extractTo($updir);
    $zip->close();
    $idx_file = $updir . '/index.php';
    $ins_file = $updir . '/__install.php';
    if (file_exists($idx_file)) {
      $obj = new stdClass();
      $obj->folder = $file_info['filename'];
      $table_name = 'pb_plugin';
      if ($action == 'themes') {
        $table_name = 'pb_theme';
      }
      $orm = new ORM();
      $orm->begin();
      $orm->add($table_name, $obj);
      $obj->id = $orm->last_id();
      if (file_exists($ins_file)) {
        require_once $ins_file;
      }
      $orm->commit();
      $orm->close();
      echo json_encode($obj);
    } else {
      Utils::rrmdir($updir);
      echo '"' . $file_info['filename'] . '": No Index File';
    }
  } else {
    Utils::rrmdir($updir);
    echo '"' . $file_info['filename'] . '": Can\'t Extract';
  }
  unlink($upload_file['tmp_name']);
}
?>